/*
 * @lc app=leetcode id=107 lang=cpp
 *
 * [107] Binary Tree Level Order Traversal II
 */
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    vector<vector<int>> levelOrderBottom(TreeNode* root) {
        vector<vector<int>> result;
        if (!root) {
            return result;
        }
        result.push_back({root->val});
        vector<TreeNode*> lv = {root};

        TreeNode *node;

        while(!lv.empty()) {

            vector<int> level;
            vector<TreeNode*> tmp;
            for (auto n:lv) {
                if (n->left) {
                    level.push_back(n->left->val);
                    tmp.push_back(n->left);
                }
                if (n->right) {
                    level.push_back(n->right->val);
                    tmp.push_back(n->right);
                }
            }
            lv = tmp;
            if(level.size() > 0)
            result.push_back(level);
        }
        reverse(result.begin(), result.end());
        return result;
        
    }
};

